<template>
  <el-dialog
    v-model="dialogVisible"
    :title="actionType === 1 ? t('inventory.check') : t('inventory.checkReview')"
    :width="isMobile ? '95%' : '500px'"
    :class="isMobile ? 'mobile-check-dialog' : ''"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      :label-width="isMobile ? '100px' : '120px'"
      :class="isMobile ? 'mobile-check-form' : ''"
    >
      <el-form-item :label="t('inventory.available_qty')">
        <el-input v-model="form.available_qty" disabled />
      </el-form-item>

      <el-form-item :label="t('inventory.lock_qty')">
        <el-input v-model="form.lock_qty" disabled />
      </el-form-item>

      <el-form-item :label="t('inventory.checkQty')" prop="check_qty">
        <el-input-number
          v-model="form.check_qty"
          :min="-(Number(form.available_qty) - Number(form.lock_qty))"
          :max="100000"
          controls-position="right"
          :disabled="actionType === 2"
          style="width: 100%"
        />
      </el-form-item>

      <el-form-item :label="t('inventory.remark')" prop="remark">
        <el-input
          v-model="form.remark"
          type="textarea"
          :rows="isMobile ? 4 : 3"
          :maxlength="300"
          :show-word-limit="true"
          :placeholder="t('inventory.remarkPlaceholder')"
          :disabled="actionType === 2"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div :class="isMobile ? 'mobile-check-footer' : ''">
        <el-button @click="dialogVisible = false">
          {{ t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ t('inventory.confirm') }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
const emit = defineEmits(['refresh'])
import { ref } from 'vue'
import { useI18n } from '@/hooks/web/useI18n'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { submitCheckApi } from '@/api/inventory'
import { useAppStore } from '@/store/modules/app'

const { t } = useI18n()

// 移动端检测
const appStore = useAppStore()
const isMobile = computed(() => appStore.getMobile)

const formRef = ref<FormInstance>()
const dialogVisible = ref(false)
const submitting = ref(false)
const actionType = ref(1) // 1 校对 2 校对审核
// 表单数据结构
const form = ref({
  id: '',
  available_qty: '0',
  lock_qty: '0',
  check_qty: 0,
  remark: ''
})

// 表单验证规则
const rules = ref<FormRules>({
  check_qty: [
    {
      required: true,
      message: t('inventory.checkQtyRequired'),
      trigger: 'blur'
    },
    {
      validator: (_, value, callback) => {
        if (0 == value) {
          callback(new Error(t('inventory.checkQty') + '不能为0'))
        } else if (value < -(Number(form.value.available_qty) - Number(form.value.lock_qty))) {
          callback(
            new Error(
              t('inventory.checkQty') +
                '不能小于' +
                -(Number(form.value.available_qty) - Number(form.value.lock_qty))
            )
          )
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  remark: [
    {
      required: true,
      message: t('inventory.remarkRequired'),
      trigger: 'blur'
    }
  ]
})

// 监听弹窗状态变化
watch(dialogVisible, (newVal) => {
  if (!newVal) {
    // 弹窗关闭时重置状态
    submitting.value = false
    formRef.value?.resetFields()
  }
})

// 处理弹窗关闭
const handleClose = (done: () => void) => {
  if (submitting.value) {
    ElMessage.warning(t('inventory.submittingWarning'))
    return
  }
  done()
}

// 打开弹窗（父组件调用）
// type: 1 校对 2 校对审核
const open = (row: any, type: number) => {
  form.value = {
    id: row.id,
    available_qty: row.available_qty,
    lock_qty: row.lock_qty,
    check_qty: type === 1 ? 0 : Number(row.check_qty),
    remark: type === 1 ? '' : row.remark
  }
  dialogVisible.value = true
  actionType.value = type
}

// 提交表单（修复后）
const handleSubmit = () => {
  formRef.value?.validate(async (valid) => {
    if (!valid) return

    submitting.value = true

    try {
      // 二次确认
      await ElMessageBox.confirm(t('inventory.confirmMessage'), t('common.tip'), {
        confirmButtonText: t('common.ok'),
        cancelButtonText: t('common.cancel'),
        type: 'warning'
      })

      // 提交数据
      const params = {
        id: Number(form.value.id),
        check_qty: Number(form.value.check_qty),
        available_qty: Number(form.value.available_qty),
        lock_qty: Number(form.value.lock_qty),
        remark: form.value.remark,
        action_type: actionType.value
      }

      await submitCheckApi(params)
      ElMessage.success(t('common.operateSucMsg'))
      dialogVisible.value = false
      emit('refresh')
    } catch (error) {
      // 处理取消操作或提交错误
      if (error !== 'cancel') {
        ElMessage.error(t('inventory.submitError'))
      }
    } finally {
      // 无论成功失败都重置按钮状态
      submitting.value = false
    }
  })
}

defineExpose({ open })
</script>

<style scoped lang="less">
// 移动端样式
@media (width <= 968px) {
  .mobile-check-dialog {
    :deep(.el-dialog) {
      max-height: 85vh;
      margin: 5vh auto;
      overflow-y: auto;
    }

    :deep(.el-dialog__header) {
      padding: 16px 20px 12px;
    }

    :deep(.el-dialog__body) {
      max-height: calc(85vh - 120px);
      padding: 0 20px 20px;
      overflow-y: auto;
    }

    :deep(.el-dialog__footer) {
      padding: 12px 20px 20px;
    }
  }

  .mobile-check-form {
    .el-form-item {
      margin-bottom: 20px;

      .el-form-item__label {
        width: 100px !important;
        line-height: 1.4;
        text-align: left;
      }

      .el-form-item__content {
        margin-left: 100px !important;
      }
    }

    // textarea 表单项调整
    .el-form-item:last-child {
      .el-form-item__label {
        align-self: flex-start;
        padding-top: 8px;
      }
    }
  }

  .mobile-check-footer {
    display: flex;
    gap: 12px;

    .el-button {
      flex: 1;
      height: 40px;
    }
  }
}

// 桌面端保持原有样式
@media (width >= 969px) {
  .mobile-check-form {
    .el-form-item {
      margin-bottom: inherit;
    }
  }
}
</style>
